import React, { Component } from "react";
import { connect } from "react-redux";
import "./WalletHome.scss";
import yhTools from "../../../tools/yh";
import MainLayout from "../../../component/mainLayout/mainLayout";
import {
	InterfaceG,
	channelCode,
	agreements_url
} from "../../../config/Config";
import {
	Checkbox,
	Toast,
	Icon,
	Modal,
	List,
	NoticeBar,
	Button
} from "antd-mobile";

import { getAppPlatformsDatas } from "../../../Redux/Action/nativeDatas/nativeDatas";
import { ThemeDefault, ThemeLife } from "../../../tools/theme";
import "react-quill/dist/quill.snow.css";

const AgreeItem = Checkbox.AgreeItem;

class WalletHome extends Component {
	constructor(props) {
		super(props);
		this.state = {
			loadStatus: "1", // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
			showDialog: "moreAccountDialog", //显示提示框

			objData: sessionStorage.getItem("walletHomeData")
				? JSON.parse(sessionStorage.getItem("walletHomeData"))
				: {
						nextProfit: "",
						nextProfitDay: "",
						rate: "0.00", // "0.00",//存款利率
						sumProfit: "0.00", //累积收益
						totalAmount: "0.00", //总金额
						totalCount: "", //总订单条数
						openStatus: "", //开户状态，0-已开户，1-未开户
						productFCode: "",
						productLabel: [], //产品标签
						productId: "",
						profitLabel: "",
						rateLabel: "",
						tradeNumber: "",
						electronicCardNo: "",
						balanceAmt: "0.00",
						productDetail: "A",
						saleStatus: 0
				  },

			visible: false,
			selected: "",
			modal1: false,
			agreeFlag: false,
			flag: true,
			popContent: <div></div>,
			notificationArr: [], //公告数据
			boardContent: "",
			boardTitle: ""
		};

		/** 是否完成数据加载
		 * 为了避免android底层框架无法并发ajax导致跳转其他界面后白屏或者界面数据异常的问题
		 * 加入该状态，跳转界面的操作都需要进行判断，必须要数据加载完成才进入*/
		this._isLoading = false;
		this._loadingTimer = null;
	}

	componentDidMount() {
		if (this.props.location.query) {
			this.setState({
				flag: false
			});
		}
		this.props._getAppPlatformsDatas({
			lnid: "1"
		});
		this.getInitData();
	}
	componentWillUnmount() {
		if (this._loadingTimer) {
			clearTimeout(this._loadingTimer);
			this._loadingTimer = null;
		}
		if (this.alert2) {
			this.alert2.close();
		}
	}

	getText() {
		let obj = {
			0: "已停售",
			1: "确认转入",
			2: "今日已售罄，请明天早点来"
		};
		return obj[this.state.objData.saleStatus];
	}
	getInitData() {
		let objs = {
			url: InterfaceG.holdingsInit,
			params: {
				channelCode: channelCode,
				productId: "1"
			},
			_alertShow: false
		};
		let _that = this;
		yhTools
			.request(objs)
			.then(res => {
				if (res.code === "0") {
					sessionStorage.setItem("walletHomeData", JSON.stringify(res.data));
					_that.setState({
						objData: res.data
					});
				} else {
					_that.setState({
						loadStatus: "3" // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败，'3'：系统正在升级）
					});
					Toast.info(res.message, 2);
				}
			})
			.then(() => {
				_that.getNotification();
			});
	}

	getNotification() {
		let objs = {
			url: "/fm/boardInfo",
			params: {
				boardType: "00",
				boardSubtype: "yhb"
			},
			_alertShow: false
		};
		// Toast.loading("加载中...", 100);
		let _that = this;
		yhTools
			.request(objs)
			.then(res => {
				if (res.code === "0") {
					_that.setState({
						notificationArr: res.data
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.then(() => {
				_that._isLoading = true;
			});
	}

	//去除br换行符
	formatText(str) {
		return str.replace(/[\<br\/\>|\<br\>]/g, "");
	}

	render() {
		const headerParams = {
			header: {
				title: "小辉宝",
				rightButt:
					this.state.objData.openStatus == "0" ? (
						<Icon type="ellipsis" />
					) : null,
				rightButtCallBack: this.showModal(),
				goToApp: this.state.flag
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: this.state.loadStatus // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};

		let {
			rate,
			sumProfit,
			totalAmount,
			openStatus,
			profitLabel,
			productLabel = [],
			nextProfitDay,
			nextProfit,
			electronicCardNo = "",
			balanceAmt = 0.0,
			productDetail
		} = this.state.objData;
		let {
			notificationArr,
			boardContent,
			boardTitle,
			popContent,
			showDialog
		} = this.state;
		// openStatus = 1;//临时调试标记，0已开通，1未开通
		return (
			<MainLayout pageParams={headerParams}>
				<div className="wallet-home-page">
					<div className="content">
						{notificationArr.length > 0 && (
							<NoticeBar
								icon=""
								marqueeProps={{
									loop: true,
									style: { padding: "0 7.5px", color: "#F5A623" }
								}}
								onClick={this.showAlert.bind(this, true)}
							>
								{
									// notificationArr.map((item, i) => {
									//     return (
									//         <span key={i}>{this.formatText(this.htmlDecodeToText(item.boardContent))}</span>
									//     );
									// })
									<span>
										{this.formatText(
											this.htmlDecodeToText(notificationArr[0].boardContent)
										)}
									</span>
								}
							</NoticeBar>
						)}
						<div className="top-div">
							<div className="top-content">
								{openStatus === "0" && (
									<div>
										<div className="line-1">
											总金额（元）
											<img
												src={require("../../../images/icon-gth.png")}
												onClick={this.openIntroduce.bind(this, 1)}
											/>
										</div>
										<div
											className="line-2"
											onClick={this.gotoNext.bind(this, 10)}
										>
											{totalAmount}
										</div>
									</div>
								)}
								{openStatus === "1" && (
									<div>
										<div
											className="line-1"
											onClick={this.gotoNext.bind(this, 3)}
										>
											存款利率
											<img
												className="line-1-arrow"
												src={require("../../../images/icon-next-arrow.png")}
											/>
										</div>
										<div className="line-2 l-120">{rate}%</div>
									</div>
								)}
								{openStatus === "0" && profitLabel == "1" && (
									<div className="top-content-tips">
										{nextProfitDay}日后预计到账<span>{nextProfit}元</span>买菜钱
										<img
											src={require("../../../images/icon-gth.png")}
											onClick={this.openIntroduce.bind(this, 2)}
										/>
									</div>
								)}
								{openStatus === "1" && productLabel.length > 0 && (
									<div className="line-3">
										{productLabel.map((item, i) => {
											return (
												<div
													className="item"
													style={ThemeLife.switch(
														{ background: "rgba(248,38,45,0.15)" },
														{}
													)}
													key={i}
												>
													{item}
												</div>
											);
										})}
									</div>
								)}

								{openStatus === "0" && (
									<div>
										<div className="line-4">
											<div
												className="item"
												onClick={this.gotoNext.bind(this, 5)}
											>
												<div className="item-top">累计收益（元）</div>
												<div className="item-bottom">{sumProfit}</div>
											</div>
											<div
												className="item"
												onClick={this.gotoNext.bind(this, 3)}
											>
												<div className="item-top">存款利率（%）</div>
												<div className="item-bottom">{rate}%</div>
											</div>
										</div>
										<div className="line-5">
											<ThemeDefault>
												<div
													className={
														this.formatMoney(totalAmount)
															? "item t-b"
															: "item t-b t-g"
													}
													onClick={this.queryXhbBankLockStatus.bind(
														this,
														1,
														InterfaceG.queryXhbRedeemBtnLockStatus
													)}
												>
													转出
												</div>
											</ThemeDefault>
											<ThemeLife>
												<div
													style={{ background: "rgba(248,38,45,0.15)" }}
													className={
														this.formatMoney(totalAmount)
															? "item t-b"
															: "item t-b t-g"
													}
													onClick={this.queryXhbBankLockStatus.bind(
														this,
														1,
														InterfaceG.queryXhbRedeemBtnLockStatus
													)}
												>
													转出
												</div>
											</ThemeLife>
											<div
												className={
													this.state.objData.saleStatus === "1"
														? "item t-w"
														: "item t-w t-g"
												}
												onClick={this.queryXhbBankLockStatus.bind(
													this,
													2,
													InterfaceG.queryXhbBuyBtnLockStatus
												)}
											>
												转入
											</div>
										</div>
									</div>
								)}
							</div>

							{openStatus === "1" && (
								<div className="top-content mt-20">
									<div className="line-6">
										<img
											className="step-img"
											src={require(`../../../images/imageXHB/${
												productDetail === "A"
													? "bg-xhb-step-a.png"
													: "bg-xhb-step-b.png"
											}`)}
										/>
										<div
											className={
												this.state.agreeFlag ? "btn-common" : "btn-disable"
											}
											onClick={this.gotoNext.bind(this, 4)}
										>
											开始赚钱
										</div>
										<div className="contract_content">
											<AgreeItem
												checked={this.state.agreeFlag}
												onChange={this.checkBoxClick.bind(this)}
											>
												阅读并同意签署
												<a onClick={this.openContract.bind(this, 1)}>
													《永辉金融隐私政策》
												</a>
												<a onClick={this.openContract.bind(this, 2)}>
													《永辉金融用户协议》
												</a>
											</AgreeItem>
										</div>
									</div>
								</div>
							)}
						</div>
						{openStatus === "0" && (
							<div>
								<div className="line-7" onClick={this.gotoNext.bind(this, 8)}>
									<img
										className="item-img"
										src={require("../../../images/imageXHB/product-purchase/icon-hua-tong-bank-logo.png")}
									/>
									<div className="item-center">
										<div className="c-1">华通银行电子账户</div>
										<div className="c-2">{electronicCardNo}</div>
									</div>
									<div className="item-right">
										<div className="r-1">可用余额{balanceAmt}元</div>
										<img
											className="next-arrow"
											src={require("../../../images/icon-next-arrow.png")}
										/>
									</div>
								</div>
								{this.state.objData.productDetail === "A" &&
									this.state.objData.paySignStatus === "0" && (
										<div
											className="line-7"
											style={{ marginTop: "0.2rem" }}
											onClick={this.gotoNext.bind(this, 9)}
										>
											<img
												className="item-img"
												src={require("../../../images/imageXHB/xhbpay-list-logo.png")}
											/>
											<div className="item-center">
												<span style={{ fontSize: "0.3rem" }}>小辉宝支付</span>
											</div>
											<div className="item-right">
												<div className="r-1">
													{this.state.objData.paySignStatus === "2"
														? "开通中"
														: this.state.objData.paySignStatus === "0"
														? "已开通"
														: "未开通"}
												</div>
												<img
													className="next-arrow"
													src={require("../../../images/icon-next-arrow.png")}
												/>
											</div>
										</div>
									)}

								<div className="line-8">
									<div className="item">
										<img
											className="item-img"
											src={require("../../../images/imageXHB/icon-azfx.png")}
										/>
										<div className="item-text">{productLabel[2]}</div>
									</div>
									<div className="item">
										<img
											className="item-img"
											src={require("../../../images/imageXHB/icon-bb.png")}
										/>
										<div className="item-text">{productLabel[1]}</div>
									</div>
									<div className="item">
										<img
											className="item-img"
											src={require("../../../images/imageXHB/icon-100qc.png")}
										/>
										<div className="item-text">{productLabel[0]}</div>
									</div>
								</div>
							</div>
						)}
					</div>
					{openStatus === "1" && (
						<div className="page-bottom">
							<div className="tips-1" onClick={this.gotoNext.bind(this, 6)}>
								常见问题
							</div>
							<div className="tips-2">本服务由福建华通银行提供</div>
						</div>
					)}
				</div>
				<div className={showDialog}>{popContent}</div>
				<Modal
					popup
					className="wallet-home-modal"
					visible={this.state.modal1}
					onClose={this.onClose("modal1")}
					animationType="slide-up"
				>
					<List className="popup-list">
						{["交易明细", "产品详情"].map((item, index) => (
							<List.Item key={index}>
								<div
									className="item"
									onClick={this.gotoPopNext.bind(this, index)}
								>
									{item}
								</div>
							</List.Item>
						))}
						<List.Item>
							<div className="cancel-btn" onClick={this.onClose("modal1")}>
								取消
							</div>
						</List.Item>
					</List>
				</Modal>
				<Modal
					visible={this.state.modal2}
					transparent
					maskClosable={false}
					className="wallet-home-modal2"
				>
					<div className="payBack-play-box">
						<div className="payBack-play-heard">
							<h2>{boardTitle}</h2>
							{/* <i onClick={this.showAlert.bind(this, false)}>X</i> */}
						</div>
						<div
							className="board-content-box ql-editor"
							style={{ textAlign: "left" }}
							dangerouslySetInnerHTML={{ __html: boardContent }}
						>
							{/* {this.state.notificationArr.map((noticeItem, noticeIndex) => {
                                return (<div className="content-d" key={noticeIndex} dangerouslySetInnerHTML={{ __html: noticeItem.boardContent }}></div>)
                            })} */}
						</div>
					</div>
					<div>
						<Button
							className="payBack-play-button"
							onClick={this.showAlert.bind(this, false)}
						>
							确定
						</Button>
					</div>
				</Modal>
			</MainLayout>
		);
	}

	showAlert(b) {
		let str,
			title = "";
		// this.state.notificationArr.map((item) => {
		//     str = str + item.boardContent;
		// });
		str = this.state.notificationArr[0].boardContent;
		title = this.state.notificationArr[0].boardTitle;
		this.setState({
			modal2: b,
			boardContent: str, // this.htmlDecode(str)
			boardTitle: title
		});
	}

	// html反转义
	htmlDecode(text) {
		let temp = document.createElement("div");
		temp.innerHTML = text;
		let output = temp.innerText || temp.textContent;
		temp = null;
		return output;
	}

	// 获取存文本
	htmlDecodeToText(text) {
		let htmlText = this.htmlDecode(text);
		htmlText = htmlText
			.replace(/<\/?.+?>/g, "")
			.replace(/\ +/g, "")
			.replace(/[\r\n]/g, "")
			.replace(/&nbsp;/gi, "")
			.replace("&nbsp;", "")
			.replace("&nsp;", "")
			.replace(/\s*/g, "");
		return htmlText;
	}

	/** 数据加载中给出的弹出，因为request插件会hide掉toast，所以目前解决方案是延时1000毫秒 */
	loadingToast() {
		if (this._loadingTimer) {
			clearTimeout(this._loadingTimer);
		}
		this._loadingTimer = setTimeout(() => {
			Toast.info("数据加载中，请稍后再试", 2);
		}, 1000);
	}

	gotoPopNext(i) {
		if (!this._isLoading) {
			this.loadingToast();
			return;
		}
		this._isLoading = false;
		let url = null;
		if (i === 0) {
			//交易明细
			url = `/billRecord/${1}`;
		} else if (i === 1) {
			//产品详情
			url = `/walletInfo/${this.state.objData.productId}`;
		}
		this.props.history.push({
			pathname: url
		});
	}

	//打开介绍
	openIntroduce(i) {
		let { productDetail } = this.state.objData;
		let str = "";
		let title = "收益说明";
		if (i === 1) {
			title = "总金额说明";
			str = (
				<div style={{ textAlign: "left" }}>
					总金额为小辉宝账户实时本金，不含派息金额，每周期派息至电子账户，提前支取时本息进入电子账户
				</div>
			);
		} else if (productDetail === "A") {
			str = (
				<div style={{ textAlign: "left" }}>
					计息周期：每周一至周日为一个计息周期。（存入与到期当周按以实际存款天数（算头不算尾）为一个计息周期。）
					<br />
					派息规则：每周一按存入时产品收益率派发上一计息周期利息，利息派发至电子账户。
					<br />
					每周期派息金额=当周期期末日终余额（每周期派息日前一天的产品日终余额）*存入时产品收益率/360*
					当周期内实际天数（算头不算尾）
					<br />
					收益率变动：收益率会根据市场情况变动，每笔存单按存入时页面显示的收益率计算收益。
					<br />
				</div>
			);
		} else {
			str = (
				<div style={{ textAlign: "left" }}>
					计息周期：自存入日（含）起每持有满一个月为一个计息周期，每满一个月按照4.8%的利率自动付息至电子账户。
					<br />
					派息规则：按月派息，提前支取时自存入日起提前支取金额按活期计息，已派发利息需扣回。
					<br />
					每期派息：利息=本金*年利率/12；到期还本付最后一期利息；到账金额=本金+本金*年利率/12
					<br />
					收益率变动：收益率会根据市场情况变动，每笔存单按存入时页面显示的收益率计算收益。
					<br />
				</div>
			);
		}
		this.alert2 = Modal.alert(title, str, [{ text: "知道了", onPress: null }]);
	}

	onSelect = opt => {
		this.setState({
			visible: false,
			selected: opt.props.value
		});
	};
	handleVisibleChange = visible => {
		this.setState({
			visible
		});
	};
	/**转入转出限制 */
	queryXhbBankLockStatus(i, requrl) {
		if (i === 1 && !this.formatMoney(this.state.objData.totalAmount)) {
			//转出
			return;
		}
		let objs = {
			url: requrl,
			params: {
				productId: this.state.objData.productId
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 15);
		yhTools
			.request(objs)
			.then(res => {
				Toast.hide();
				if (res.code === "0") {
					this.gotoNext(i);
				} else {
					Toast.info(res.message, 2);
				}
			})
			.then(() => {
				this._isLoading = true;
			});
	}

	gotoNext(i) {
		if (!this._isLoading) {
			this.loadingToast();
			return;
		}

		let pageParams = {};
		if (i === 1) {
			//转出
			if (!this.formatMoney(this.state.objData.totalAmount)) {
				return;
			}
			// 判断已签约，并且有合并的订单才能进入一键转出界面
			if (
				this.state.objData.paySignStatus === "0" &&
				this.state.objData.mergeStatus == "0"
			) {
				//已开通
				pageParams = {
					url: `/transferXHBOutByPay/${this.state.objData.productId || ""}`
				};
			} else {
				//需要调用接口判断是否签约小辉宝支付
				pageParams = {
					url: `/depositDetail`
				};
			}
		} else if (i === 10) {
			if (!this.formatMoney(this.state.objData.totalAmount)) {
				return;
			}
			pageParams = {
				url: `/depositDetail`
			};
		} else if (i === 2) {
			//转入
			if (this.state.objData.saleStatus != "1") {
				Toast.info(this.getText(), 2);
				return;
			}
			pageParams = {
				url: `/transferXHBInto/${this.state.objData.productId || ""}`
			};
		} else if (i === 3) {
			pageParams = {
				url: `/walletInfo/${this.state.objData.productId || ""}`
			};
		} else if (i === 4) {
			if (!this.state.agreeFlag) {
				return;
			}
			this.appBtnMoney();
		} else if (i === 5) {
			pageParams = {
				url: `/cumulativeIncome`
			};
		} else if (i === 6) {
			pageParams = {
				url: `/xhbPorblem/${this.state.objData.productDetail}`
			};
		} else if (i === 7) {
			pageParams = {
				url: `/depositDetail`
			};
		} else if (i === 8) {
			pageParams = {
				url: `/bankDetailPage`
			};
		} else if (i === 9) {
			if (this.state.objData.paySignStatus === "2") {
				//开通中
				pageParams = {
					url: `/signRes`
				};
			} else if (this.state.objData.paySignStatus === "0") {
				//已开通
				pageParams = {
					url: `/payDetail`
				};
			} else {
				//未开通
				pageParams = {
					url: `/signXHB`
				};
			}
		}
		this._isLoading = false;
		this.props.history.push({
			pathname: pageParams.url
		});
	}

	//开始赚钱点击接口
	appBtnMoney() {
		let objs = {
			url: InterfaceG.xhbVerifyIdentity,
			params: {
				channelCode,
				version: "1.0"
			}
		};
		let _that = this;
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				const { pageNo, userName, idNo, mobilePhone, signDate } = res.data;
				if (pageNo === "01") {
					// 开户
					_that.props.history.push({
						pathname: `/uploadIDCardImgPage`
					});
				} else if (pageNo === "02") {
					// 身份核实
					_that.props.history.push({
						pathname: `/identityVerification`,
						state: { userName, idNo, mobilePhone, signDate }
					});
				} else {
					Toast.info("pageNo错误" + pageNo, 2);
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}

	//勾选协议
	checkBoxClick(e) {
		this.setState({
			agreeFlag: e.target.checked
		});
	}

	//查看协议
	openContract(v) {
		if (v === 1) {
			this.props.history.push({
				pathname: "/iframeAgreements",
				state: {
					src: agreements_url + "/privacyAgreement.html",
					title: "永辉金融隐私政策"
				}
			}); //《用户隐私协议》
		} else if (v === 2) {
			this.props.history.push(`/serviceAgreementAuthorization`); //《客户服务协议》
		}
	}

	showModal = () => () => {
		// e.preventDefault(); // 修复 Android 上点击穿透
		this.setState({
			showDialog: "moreAccountDialog  wrapper-out",
			popContent: "",
			modal1: true
		});
	};
	onClose = () => () => {
		this.setState({
			modal1: false
		});
	};

	formatMoney(str) {
		return Number(str.replace(/,/g, "")) > 0;
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_getAppPlatformsDatas: abj => {
			//获取native的数据
			dispatch(getAppPlatformsDatas(abj));
		}
	};
}

const WalletHomePage = connect(mapStateToProps, mapDispatchToProps)(WalletHome);
export default WalletHomePage;
